package org.lgiavedoni.android.franq.util.classU;

import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang.ClassUtils;
import org.lgiavedoni.android.franq.service.log.Logger;

public class ClassUtil {

	public static Class getLastSuperClass(Class clazz) {
		try {
			return (Class) ClassUtils.getAllSuperclasses(clazz).get(0);
		} catch (Exception e) {
			return clazz;
		}
	}

	public static void setProperties(Object objInstance, Map<String, String> properties) {
		if (properties == null || properties.size() == 0)
			return;
		try {
			for (Method m : objInstance.getClass().getMethods()) {
				if (isSetterMethod(m)) {
					for (String property : properties.keySet())
						if (m.getName().toLowerCase().endsWith("set" + property.toLowerCase())) {
							Class paramClass = m.getParameterTypes()[0];
							Object param = null;
							if (paramClass.equals(Boolean.class))
								param = new Boolean(properties.get(property));
							if (paramClass.equals(Long.class))
								param = new Long(properties.get(property));
							if (paramClass.equals(Integer.class))
								param = new Integer(properties.get(property));
							if (paramClass.equals(String.class))
								param = properties;
							m.invoke(objInstance, param);
						}
				}
			}
		} catch (Exception e) {
			Logger.inst.error(e);
		}
	}

	private static boolean isSetterMethod(Method m) {
		return m.getName().toLowerCase().startsWith("set");
	}

	public static boolean isInstanceOf(Class clazz1, Class clazz2) {
		for (Class c : clazz1.getInterfaces()) {
			if (c.getCanonicalName().equals(clazz2.getCanonicalName())) {
				return true;
			}
		}

		if (clazz1.getSuperclass() != null && clazz1.getSuperclass().getCanonicalName().equals(clazz2.getCanonicalName())) {
			return true;
		}
		return false;
	}

}
